import React, { useState, useRef, useEffect } from 'react'
import { NavBar } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import { Button } from 'react-vant'
import { ActionSheet } from 'react-vant'
import Addressinfo from './addressInfo/Addressinfo'
import { useSelector } from 'react-redux'
import Addresslist from './addressList/Addresslist'
import { useCascaderAreaData } from '@vant/area-data';

export default function Address() {
    let { userId } = useSelector(state => state.user)
    const navigate = useNavigate()
    const listRef = useRef()
    const infoRef = useRef()
    const cascaderAreaData = useCascaderAreaData();
    const [visible, setVisible] = useState(false)
    const [type, setType] = useState('ADD')
    const [values, setValues] = useState({});
    const onCancel = () => setVisible(false)
    const back = () => {
        navigate(-1)
    }

    useEffect(() => {
        infoRef?.current?.setFieldsValue(values)
    }, [values.userid])

    const Edit = (values) => {
        console.log(values);
        let province = cascaderAreaData.find(item => item.text === values.province)
        let city = province.children.find(item => item.text === values.city)
        let county = city.children.find(item => item.text === values.county)
        let area = [province.value, city.value, county.value]
        values.area = area
        console.log(values);
        setValues(values);
        setType('EDIT')
        infoRef?.current?.setFieldsValue(values)
        setVisible(true)
    }
    const colse = () => {
        infoRef?.current?.setFieldsValue({
            addressDetail: '',
            area: [],
            isDefault: false,
            name: '',
            tel: ''
        })
    }
    return (
        <div>
            <NavBar style={{ backgroundColor: '#fff' }} back='返回' onBack={back}>
                地址
            </NavBar>
            <Addresslist userId={userId} ref={listRef} Edit={Edit} />
            <Button onClick={() => { setVisible(true); setType('ADD'); setValues({ userid: userId }) }} type='danger' block round style={{ position: 'fixed', bottom: 0, width: '90%', margin: '5px 5%' }}>
                新增地址
            </Button>
            {values.userid && <ActionSheet onClosed={colse} visible={visible} onCancel={onCancel}>
                <Addressinfo setVisible={setVisible} ref={infoRef} type={type} addressid={values.addressid} userId={userId} getAddressList={listRef?.current?.getAddressList} addresslist={listRef?.current?.addresslist} />
            </ActionSheet>}

        </div>
    )
}
